<template>
  <a-modal ref="basicModel" v-model:visible="isVisible" v-bind="getBindValue"  @cancel="onCloseModal">
    <template #title>
      <div class="w-full cursor-move basic-modal-bar" ref="basicModalBar">{{ getBindValue?.title }}</div>
    </template>
    <template #default>
      <slot name="default"></slot>
    </template>
    <template #footer v-if="!$slots.footer">
      <a-space>
        <a-button @click="closeModal">取消</a-button>
        <a-button type="primary" :loading="subLoading" @click="handleSubmit">
          {{ subBtuText }}
        </a-button>
      </a-space>
    </template>
    <template v-else #footer>
      <slot name="action"></slot>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import {
    getCurrentInstance,
    nextTick,
    unref,
    computed,
    useAttrs,
    defineEmits,
    defineProps,
  } from 'vue';
  import { basicProps } from './props';
  import { startDrag } from '@/utils/Drag';
  import { deepMerge } from '@/utils';
  import { FormProps } from '@/components/Form';
  import { ModalProps, ModalMethods } from './type';
  import { useDraggable } from '@vueuse/core';


  const attrs = useAttrs();
  const props = defineProps({ ...basicProps });
  const emit = defineEmits(['on-cancel', 'on-ok', 'register']);

  let basicModel = $ref<HTMLElement>();
  let basicModalBar = $ref<HTMLElement>();

  let propsRef = $ref();

  let isVisible = $ref(false);
  let subLoading = $ref(false);

  const getProps = computed((): FormProps => {
    return { ...props, ...(unref(propsRef) as any) };
  });

  const subBtuText = computed(() => {
    const { subBtuText } = propsRef as any;
    return subBtuText || props.subBtuText;
  });

  async function setProps(modalProps: Partial<ModalProps>): Promise<void> {
    propsRef = deepMerge(unref(propsRef) || ({} as any), modalProps);
  }

  const getBindValue: any = computed(() => {
    return {
      ...attrs,
      ...unref(getProps),
      ...unref(propsRef),
    };
  });

  function setSubLoading(status: boolean) {
    subLoading = status;
  }

  function openModal() {
    isVisible = true;
    nextTick(() => {
      const oBox = document.querySelector('.ant-modal-root');
      const oBar = document.querySelector('.ant-modal-title');
      // console.log(oBox, oBar, basicModel);
      // startDrag(oBar, oBox);
      // useDraggable(basicModel);

      const { x, y, isDragging } = useDraggable(basicModalBar);
    });
  }

  function closeModal() {
    isVisible = false;
    subLoading = false;
    emit('on-cancel');
  }

  function onCloseModal() {
    isVisible = false;
    emit('on-cancel');
  }

  function handleSubmit() {
    subLoading = true;
    emit('on-ok');
  }

  const modalMethods: ModalMethods = {
    setProps,
    openModal,
    closeModal,
    setSubLoading,
  };

  const instance = getCurrentInstance();
  if (instance) {
    emit('register', modalMethods);
  }


</script>

<style lang="less">
  .cursor-move {
    cursor: move;
  }
</style>
